package controllers

import (
	// "encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

type InitpController struct {
	MainController
}

func getFilelist(path string) (gPath []string) {
	// gPath := []string{}
	err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			return nil
		}
		gPath = append(gPath, path)
		// fmt.Println(gPath)
		return nil
	})

	if err != nil {
		fmt.Printf("filepath.Walk() returned %v\n", err)
	}
	return gPath
}

func CopyFile(src, des string) (w int64, err error) {
	srcFile, err := os.Open(src)
	if err != nil {
		fmt.Println(err)
	}
	defer srcFile.Close()

	desFile, err := os.Create(des)
	if err != nil {
		fmt.Println(err)
	}
	defer desFile.Close()

	return io.Copy(desFile, srcFile)
}

func RemoveFile() bool {
	paths := ".\\static\\img\\users"
	err := filepath.Walk(paths, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			return nil
		}
		err2 := os.Remove(path) //删除文件test.txt
		if err2 != nil {
			//如果删除失败则输出 file remove Error!
			fmt.Println("file remove Error!")
			//输出错误详细信息
			fmt.Printf("%s", err)
		} else {
			//如果删除成功则输出 file remove OK!
			fmt.Print("file remove OK!")
		}
		return nil
	})

	if err != nil {
		fmt.Printf("filepath.Walk() returned %v\n", err)
	}
	return true
}

func InitUser() (s map[string]interface{}, num int) {
	RemoveFile()
	s = map[string]interface{}{}
	path := getFilelist(".\\static\\img\\user")
	for k, v := range path {
		pathList := strings.Split(v, "\\")
		fileName := pathList[len(pathList)-1]
		name := strings.Split(fileName, ".")[0]
		id := strconv.Itoa(k)
		imgUrl := ".\\static\\img\\users\\" + id + ".png"
		w, err := CopyFile(".\\static\\img\\user\\"+fileName, ".\\static\\img\\users\\"+strconv.Itoa(k)+".png")
		if err != nil {
			fmt.Println(err.Error())
		}
		s[id] = map[string]string{"Name": name, "Id": id, "ImgUrl": imgUrl}
		fmt.Println(w)
	}
	fmt.Println(s)
	num = len(s)
	fmt.Println(num)
	// b, err := json.Marshal(s)
	// if err != nil {
	// 	fmt.Println("json err:", err)
	// }
	initFile := ".\\models\\data\\initFile.json"
	OutJson(initFile, s)
	initFile1 := ".\\models\\data\\1.json"
	initFile2 := ".\\models\\data\\2.json"
	initFile3 := ".\\models\\data\\3.json"
	OutJson(initFile1, map[string]interface{}{})
	OutJson(initFile2, map[string]interface{}{})
	OutJson(initFile3, map[string]interface{}{})
	// fmt.Println(string(b))
	return s, num
}

func (this *InitpController) Post() {
	InitUser()
	this.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "success"}
	this.ServeJSON()
	return
}
